'''
Created on Jan 12, 2011

@author: Jonthan Herbst
'''

from threading import Thread

import GoogleC2DM, Messages, SQSReceiver


from HardwareInterface import HardwareSimulator
from Utilities import BlockingPopThreadSafeQueue
    
class Simulator():
    
    _queueName = "myqueue2"
    _registrationId = None
    
    def Main(self):
        hardwareSimulator = HardwareSimulator()
        
    
    def sendAlert(self):
        print "Get Registration Id"
        if self._registrationId is None:
            self._GetRegistrationId()
            
        gC2DM = GoogleC2DM.GoogleC2DM(self._registrationId)
        alertMessage = Messages.EntrantDetected("192.168.0.1", "8000", self._queueName)
        
        print "Sending Alert Message"
        gC2DM.sendMessage(alertMessage.renderMessage())
        
    def GetMessages(self):
        reciever = SQSReciever.SQSReciever(self._queueName)
        messages = reciever.recieveMessage()
        if messages:
            return messages
        else:
            print "Timeout: No Messages Received"
        return None
    
    def _GetRegistrationId(self):
        registrationMessage = None
        
        while registrationMessage is None:
            messages = self.GetMessages()
            for message in messages:
                tempMessage = Messages.parseMessage(message)
                print tempMessage.renderMessage()
                if tempMessage.__class__ == Messages.C2DMRegistration:
                    registrationMessage = tempMessage
        
        self._registrationId = registrationMessage.m_registrationId
        
if __name__ == "__main__":
    sim = Simulator()
    sim.sendAlert()
    print "Getting response"
    messages = sim.GetMessages()
    if not messages:
        print "Timeout, access denied"
    else:
        for message in messages:
            parsedMessage = Messages.parseMessage(message)
            if parsedMessage.__class__ == Messages.DoorCommand:
                print "Door Action Received:", parsedMessage.m_action
    